package com.ruoyi.heytalk.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.heytalk.ImFriend;
import com.ruoyi.common.core.domain.heytalk.dto.FriendSetBlackDTO;
import com.ruoyi.common.core.domain.heytalk.dto.FriendSetMomentAuthDTO;
import com.ruoyi.common.core.domain.heytalk.dto.FriendSetStarDTO;
import com.ruoyi.common.core.domain.heytalk.vo.LoginImUser;
import com.ruoyi.common.core.domain.heytalk.vo.MailFriendListVO;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.core.service.HeyTalkTokenService;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.heytalk.mapper.ImFriendMapper;
import com.ruoyi.heytalk.service.IImFriendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 朋友信息Service业务层处理
 * 
 * @author ruoyi
 * @since 2021-10-17
 */
@Slf4j
@Service
@DataSource(value = DataSourceType.SLAVE)
public class ImFriendServiceImpl extends ServicePlusImpl<ImFriendMapper, ImFriend, ImFriend> implements IImFriendService {

    @Resource
    private HeyTalkTokenService tokenService;

    @Override
    public AjaxResult<List<MailFriendListVO>> friendList() {
        LoginImUser loginImUser = tokenService.getLoginImUser(ServletUtils.getRequest());
        List<ImFriend> friendList = this.list(new LambdaQueryWrapper<ImFriend>().eq(ImFriend::getUserId, loginImUser.getUserId())
                .groupBy(ImFriend::getNickRemarkInitial).select(ImFriend::getNickRemarkInitial).orderByAsc(ImFriend::getNickRemarkInitial));
        List<MailFriendListVO> mailFriendListVOS = BeanUtil.copyToList(friendList, MailFriendListVO.class);
        List<ImFriend> friends = this.list(new LambdaQueryWrapper<ImFriend>().eq(ImFriend::getUserId, loginImUser.getUserId()));
        mailFriendListVOS.stream().forEach(mailFriendListVO -> {
            mailFriendListVO.setFriendList(friends.stream().filter(f->mailFriendListVO.getNickRemarkInitial().equals(f.getNickRemarkInitial())).collect(Collectors.toList()));
        });
        return AjaxResult.success(mailFriendListVOS);
    }

    @Override
    public AjaxResult<Void> friendSetBlack(FriendSetBlackDTO friendSetBlackDTO) {
        try {
            LoginImUser loginImUser = tokenService.getLoginImUser(ServletUtils.getRequest());
            ImFriend imFriend = this.getOne(new LambdaQueryWrapper<ImFriend>()
                    .eq(ImFriend::getFriendId, friendSetBlackDTO.getFriendId())
                    .eq(ImFriend::getUserId, loginImUser.getUserId()));
            if (Objects.isNull(imFriend)) {
                AjaxResult.error(MessageUtils.message("heyTalk.data.null"), null);
            }
            return this.update(ImFriend.builder().isBlack(friendSetBlackDTO.getIsBlack()).build(),
                    new LambdaQueryWrapper<ImFriend>().eq(ImFriend::getId, imFriend.getId()))? AjaxResult.success() : AjaxResult.error();
        } catch (Exception e) {
            log.error("移入/移除黑名单失败:{}", e);
            throw new ServiceException(MessageUtils.message("heyTalk.isBlack.err"));
        }
    }

    @Override
    public AjaxResult<Void> friendSetStar(FriendSetStarDTO friendSetStarDTO) {
        try {
            LoginImUser loginImUser = tokenService.getLoginImUser(ServletUtils.getRequest());
            ImFriend imFriend = this.getOne(new LambdaQueryWrapper<ImFriend>()
                    .eq(ImFriend::getFriendId, friendSetStarDTO.getFriendId())
                    .eq(ImFriend::getUserId, loginImUser.getUserId()));
            if (Objects.isNull(imFriend)) {
                AjaxResult.error(MessageUtils.message("heyTalk.data.null"), null);
            }
            return this.update(ImFriend.builder().isBlack(friendSetStarDTO.getStar()).build(),
                    new LambdaQueryWrapper<ImFriend>().eq(ImFriend::getId, imFriend.getId()))? AjaxResult.success() : AjaxResult.error();
        } catch (Exception e) {
            log.error("设置/取消星标好友失败:{}", e);
            throw new ServiceException(MessageUtils.message("heyTalk.star.err"));
        }
    }

    @Override
    public AjaxResult<Void> friendSetMomentAuth(FriendSetMomentAuthDTO friendSetMomentAuthDTO) {
        try {
            LoginImUser loginImUser = tokenService.getLoginImUser(ServletUtils.getRequest());
            ImFriend imFriend = this.getOne(new LambdaQueryWrapper<ImFriend>()
                    .eq(ImFriend::getFriendId, friendSetMomentAuthDTO.getFriendId())
                    .eq(ImFriend::getUserId, loginImUser.getUserId()));
            if (Objects.isNull(imFriend)) {
                AjaxResult.error(MessageUtils.message("heyTalk.data.null"), null);
            }
            return this.update(ImFriend.builder().lookMe(friendSetMomentAuthDTO.getLookMe()).lookHim(friendSetMomentAuthDTO.getLookHim()).build(),
                    new LambdaQueryWrapper<ImFriend>().eq(ImFriend::getId, imFriend.getId()))? AjaxResult.success() : AjaxResult.error();
        } catch (Exception e) {
            log.error("设置朋友圈权限失败:{}", e);
            throw new ServiceException("设置朋友圈权限失败");
        }
    }

}
